package com.xidian.zhiancloud.controller.ledgerManagerment.targetAndSystem;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xidian.zhiancloud.controller.base.BaseController;
import com.xidian.zhiancloud.dto.ResultDTO;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.model.SecurityMeetingLedger;
import com.xidian.zhiancloud.model.syset.Organization;
import com.xidian.zhiancloud.model.syset.SysUser;
import com.xidian.zhiancloud.qo.ledgerManagerment.targetAndSystem.SecurityMeetingLedgerQO;
import com.xidian.zhiancloud.service.ledgerManager.targerAndSystem.SecurityMeetingLedgerService;
import com.xidian.zhiancloud.service.user.UserService;
import com.xidian.zhiancloud.service.user.usermanage.OrganizationService;
import com.xidian.zhiancloud.util.zyf.StringUtils;
import com.xidian.zhiancloud.vo.ledgerManagerment.targetAndSystem.SecurityMeetingLedgerVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 台账管理 目标职责与制度 安全会议台账
 *
 * @Author: Summerless
 * @Date: 2020/11/9 11:32
 */
@RestController
@RequestMapping("/SecurityMeetingLedger")
public class SecurityMeetingLedgerController extends BaseController {
    @Autowired
    private SecurityMeetingLedgerService securityMeetingLedgerService;

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private UserService userService;

    /**
     * 添加安全会议台账对象
     *
     * @param securityMeetingLedger 安全会议台账对象
     * @return 是否添加成功
     */
    @PostMapping("/add")
    public ResultDTO<Boolean> add(SecurityMeetingLedger securityMeetingLedger) {
        securityMeetingLedger.setCompanyId(getSessionUserCompanyId());
        securityMeetingLedger.setCreatorId(getSessionUserid());
        securityMeetingLedger.setCreateTime(new Date(System.currentTimeMillis()));
        Boolean res = securityMeetingLedgerService.save(securityMeetingLedger);
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }

    /**
     * 根据id获取安全会议台账对象
     *
     * @param id 安全会议台账对象的id
     * @return 安全会议台账对象
     */
    @GetMapping("/getById")
    public ResultDTO<SecurityMeetingLedgerVO> getById(@RequestParam("id") Long id) {
        return ResultDTO.successOf(securityMeetingLedgerService.getVOById(id), GeneralResponseEnums.SUCCESS);
    }

    /**
     * 根据id列表删除安全会议台账对象
     *
     * @param ids 安全会议台账对象的id列表
     * @return 是否删除成功
     */
    @PostMapping("/deleteByIds")
    public ResultDTO<Boolean> deleteByIds(Long[] ids) {
        Boolean res = securityMeetingLedgerService.removeByIds(Arrays.asList(ids));
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }

    /**
     * 修改安全会议台账对象
     *
     * @param securityMeetingLedger 安全会议台账对象
     * @return 是否修改成功
     */
    @PostMapping("/patchById")
    public ResultDTO<Boolean> patchById(SecurityMeetingLedger securityMeetingLedger) {
        securityMeetingLedger.setCreatorId(null);
        securityMeetingLedger.setCompanyId(null);
        securityMeetingLedger.setCreateTime(null);
        Boolean res = securityMeetingLedgerService.updateById(securityMeetingLedger);
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }

    /**
     * 列表查询
     *
     * @param securityMeetingLedgerQO 查询参数
     * @return 安全会议台账列表
     */
    @GetMapping("/getListByQO")
    public ResultDTO<IPage<SecurityMeetingLedgerVO>> getList(SecurityMeetingLedgerQO securityMeetingLedgerQO) {
        if (securityMeetingLedgerQO.getCurrent() == null || securityMeetingLedgerQO.getSize() == null) {
            return ResultDTO.errorOf(GeneralResponseEnums.REQUEST_ERROR);
        }
        securityMeetingLedgerQO.setCompanyId(getSessionUserCompanyId());
        return ResultDTO.successOf(securityMeetingLedgerService.selectByQO(securityMeetingLedgerQO), GeneralResponseEnums.SUCCESS);
    }

    /**
     * 导出
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response, Long[] ids) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("安全会议台账导出", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        List<SecurityMeetingLedger> list = securityMeetingLedgerService.listByIds(Arrays.asList(ids));
        List<SecurityMeetingLedgerVO> ans = new LinkedList<>();
        list.forEach(t -> {
            SecurityMeetingLedgerVO vo = new SecurityMeetingLedgerVO();
            BeanUtils.copyProperties(t, vo);
            List<Organization> organizations = organizationService.listByIds(Arrays.stream(vo.getParticipateOrganizationIds().split(",")).collect(Collectors.toList()));
            List<String> organizationNames = organizations.stream().map(Organization::getName).collect(Collectors.toList());
            vo.setParticipateOrganizationNames(StringUtils.concatStrings(organizationNames));
            List<SysUser> users = userService.listByIds(Arrays.stream(vo.getPeoIds().split(",")).collect(Collectors.toList()));
            List<String> userNames = users.stream().map(SysUser::getName).collect(Collectors.toList());
            vo.setPeoNames(StringUtils.concatStrings(userNames));

            SysUser moderator = userService.getById(vo.getModeratorId());
            vo.setModeratorName(moderator == null ? "该用户已被删除" : moderator.getName());

            SysUser recorder = userService.getById(vo.getRecorderId());
            vo.setRecorderName(recorder == null ? "该用户已被删除" : recorder.getName());
            ans.add(vo);
        });
        System.out.println(list.size());
        EasyExcel.write(response.getOutputStream(), SecurityMeetingLedgerVO.class).sheet("模板").doWrite(ans);
    }

    /**
     * 导入
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public ResultDTO<Boolean> upload(@RequestParam("file") MultipartFile file) throws IOException {
        List<SecurityMeetingLedgerVO> list = EasyExcel.read(file.getInputStream()).head(SecurityMeetingLedgerVO.class).sheet().doReadSync();
        List<SecurityMeetingLedger> ans = new LinkedList<>();
        list.forEach(vo -> {
            SecurityMeetingLedger ledger = new SecurityMeetingLedger();
            BeanUtils.copyProperties(vo, ledger);
            ledger.setCreatorId(getSessionUserid());
            ledger.setCompanyId(getSessionUserCompanyId());
            ledger.setCreateTime(new Date(System.currentTimeMillis()));
            String[] orgnames = vo.getParticipateOrganizationNames().split(",");
            List<Long> orgids = new LinkedList<>();
            for (String name : orgnames) {
                LambdaQueryWrapper<Organization> organizationLambdaQueryWrapper = Wrappers.<Organization>lambdaQuery();
                organizationLambdaQueryWrapper.eq(Organization::getName, name);
                Organization organization = organizationService.getOne(organizationLambdaQueryWrapper);
                if (organization != null) {
                    orgids.add(organization.getId());
                }
            }
            ledger.setParticipateOrganizationIds(StringUtils.concatLongs(orgids));

            String[] peonames = vo.getPeoNames().split(",");
            List<Long> peoids = new LinkedList<>();
            for (String name : peonames) {
                LambdaQueryWrapper<SysUser> userLambdaQueryWrapper = Wrappers.<SysUser>lambdaQuery();
                userLambdaQueryWrapper.eq(SysUser::getName, name);
                SysUser user = userService.getOne(userLambdaQueryWrapper);
                if (user != null) {
                    peoids.add(user.getId());
                }
            }
            ledger.setPeoIds(StringUtils.concatLongs(peoids));
            LambdaQueryWrapper<SysUser> query = Wrappers.<SysUser>lambdaQuery();
            query.eq(SysUser::getName, vo.getModeratorName());
            SysUser moderator = userService.getOne(query);
            ledger.setModeratorId(moderator == null ? null : moderator.getId());

            LambdaQueryWrapper<SysUser> query1 = Wrappers.<SysUser>lambdaQuery();
            query1.eq(SysUser::getName, vo.getRecorderName());
            SysUser recorder = userService.getOne(query1);
            ledger.setRecorderId(recorder == null ? null : recorder.getId());
            ans.add(ledger);
        });
        Boolean res = securityMeetingLedgerService.saveBatch(ans);
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }
}
